// 导入数据库操作模块
const db = require('../db/index');

// 创建房间函数
exports.createRoom = (req, res) => {
  const sqlAdd = 'insert into room_list set ?';
  db.query(sqlAdd, { roomName: req.body.roomName, userId: req.body.userId }, (err, result) => {
    if (err) return res.cc(err);
    // 判断影响行数是否为1
    if (result.affectedRows != 1) return res.cc('创建失败，请稍后重试', 500);
    // 注册用户成功
    res.cc('创建成功');
  });
};

// 查询房间列表
exports.roomQuery = (req, res) => {
  const sql = `select * from room_list where userId=? and deleteTag != 1`;
  db.query(sql, req.query.userId, (err, result) => {
    if (err) return res.cc(err, 500);
    if (result.length >= 0) {
      return res.send({ code: 200, data: result, total: result.length });
    }
    res.cc('查询失败', 500);
  });
};

// 删除房间
exports.roomDelete = (req, res) => {
  const sql = 'UPDATE room_list SET deleteTag = ? WHERE roomId = ? AND userId = ?';
  // 从请求体中获取参数
  const { deleteTag, roomId, userId } = req.query;
  // 执行 SQL 更新
  db.query(sql, [deleteTag, roomId, userId], (err, result) => {
    if (err) return res.cc(err);
    // 判断是否成功更新
    if (result.affectedRows !== 1) {
      return res.cc('删除失败', 400);
    }
    res.cc('删除成功', 200);
  });
};